package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.PageParams;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增分类，
     *
     * @param category
     * @return
     */
    @PostMapping
    public R save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分类查询
     *
     * @param pageParams
     * @return
     */
    @GetMapping("/page")
    public R selectPage(PageParams pageParams) {
        try {
            IPage<Category> categoryIPage = categoryService.selectPage(pageParams);
            return R.success(categoryIPage);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("分页查询失败");
        }
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteCategory(Long id) {
        System.out.println("参数id");
        System.out.println(id);
        int count1 = dishService.selectByCategoryId(id);
        if (count1 > 0) {
            throw new CustomException("此分类关联菜品，禁止删除");
    }
       int count2= setmealService.selectByCategoryId(id);
        if (count2 > 0) {
            throw new CustomException("此分类关联菜品，禁止删除");
        }
        int rows = categoryService.deleteCategory(id);
        return R.success(rows);
    }

    /**
     * 修改category
     */
    @PutMapping
    public R update(@RequestBody Category category) {
        int rows = categoryService.update(category);
        return R.success(rows);
    }
    @GetMapping("/list")
    public R list(Category category){
       List<Category> list= categoryService.list(category);
       return R.success(list);

    }
}
